package io.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONConnector {
	/**
	 * Base url
	 * TODO Need to change this to "", but first call setBaseUrl(String url) from activitys
	 */
	private String baseUrl = "http://frankkie.nl/basewars/api/v4/";

	/**
	 * Interface for http client
	 */
	private HttpClient httpclient;

	/** 
	 * result from the HTTP request
	 */
	private String result = "";

	/**
	 * Error code
	 */
	private BasicResponseHandler handler;
	
	public JSONConnector()
	{
		this.httpclient = new DefaultHttpClient();
	}
	
	/**
	 * Get the webservice url
	 * @return String
	 */
	public String getBaseUrl() {
		return baseUrl;
	}

	/**
	 * Set the webservice url, you need to end with "/"
	 * @param baseUrl String 
	 */
	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}
	
	/**
	 * HTTP GET
	 * @param uri The uri within the webservice (don't start with "/" you can end with "/" if you want )
	 * @return result from the webservice
	 */
	public JSONObject requestGetObject(String uri) 
	{
		HttpGet request = new HttpGet(this.baseUrl + uri);
		handler = new BasicResponseHandler();
		JSONObject jsonObject = null;
	
		// your result will be String :
	    try {
			result = httpclient.execute(request, handler);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try 
		{
			jsonObject = new JSONObject(result);			
		} catch (JSONException e) 
		{
			e.printStackTrace();
		} 
		
		return jsonObject;
	}
	
	/**
	 * HTTP POST
	 * @param uri
	 * @param params
	 * @return JSONObject from the webservice 
	 */
	public JSONObject requestPostObject(String uri, List<NameValuePair> params) {
	    // Create a new HttpClient and Post Header
	    String postURL = this.baseUrl + uri;
	    JSONObject jsonObject;

	    try {
	        // Add your data
	    	HttpPost httppost = new HttpPost(postURL);
	        httppost.setEntity(new UrlEncodedFormEntity(params));

	        // Execute HTTP Post Request
			HttpResponse response = httpclient.execute(httppost);
	       
	       
			jsonObject = new JSONObject(convertStreamToString(response.getEntity().getContent()).toString());
	        
	    } catch (Exception e) {
	    	e.printStackTrace();
	        // TODO Auto-generated catch block
	    	jsonObject = new JSONObject();
	    }
	    
	    return jsonObject;
	} 
	
    /**
     * Convert stream to string
     * 
     * @param is InputStream
     * @return
     */
	private String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
        	while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {	
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
	
	
	/**
     * Execute httpget
	 *
     * @param url
     * @param category JSON object catgory name
     * @param replace Replace character with {[
     * 
     * @return 		Array
     */
    public JSONArray connect(String url, String category, boolean replace)
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(baseUrl+url); 
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            //Log.i("Praeda",response.getStatusLine().toString());
            HttpEntity entity = response.getEntity();
            if (entity != null) {
 
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                if (replace == true) {
                	result = result.replace(":{", ":[{");
                    result = result.replace("\"}", "\"}]");
                } else {
                	
                }	
                JSONObject json=new JSONObject(result);
                JSONArray nameArray=json.getJSONArray(category);
                
                instream.close();
                
        		return nameArray;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
		return null;
    }
}